package com.imooc.service.impl;

import com.imooc.enums.Sex;
import com.imooc.mapper.UsersMapper;
import com.imooc.pojo.BO.UserBO;
import com.imooc.pojo.Users;
import com.imooc.service.UserService;
import com.imooc.utils.DateUtil;
import com.imooc.utils.MD5Utils;
import org.n3r.idworker.Sid;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author lihongyu
 * @CreateTime 2021-08-06 12:57
 * @Description 用户业务逻辑实现类
 */
@Service
public class UserServiceImpl implements UserService {

    /**
     * 用户默认头像
     */
    private static final String USER_FACE = "http://122.152.205.72:88/group1/M00/00/05/CpoxxFw_8_qAIlFXAAAcIhVPdSg994.png";

    @Resource
    private UsersMapper usersMapper;

    @Resource
    private Sid sid;

    /**
     * 校验用户名是否存在
     *
     * @param userName 用户名
     * @return 存在/不存在
     */
    @Override
    public boolean validateUserNameIsExist(String userName) {
        Example example = new Example(Users.class);
        example.createCriteria().andEqualTo("username",userName);
        Users users = usersMapper.selectOneByExample(example);
        return users != null;
    }

    /**
     * 创建用户
     * @param userBO 用户注册封装实体
     * @return 用户对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Users createUser(UserBO userBO) {
        String userId = sid.nextShort();
        Users user = new Users();
        user.setId(userId);
        user.setUsername(userBO.getUsername());
        try {
            user.setPassword(MD5Utils.getMD5Str(userBO.getPassword()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 默认用户昵称同用户名
        user.setNickname(userBO.getUsername());
        // 默认头像
        user.setFace(USER_FACE);
        // 默认生日
        user.setBirthday(DateUtil.stringToDate("1900-01-01"));
        // 默认性别为 保密
        user.setSex(Sex.secret.type);
        user.setCreatedTime(new Date());
        user.setUpdatedTime(new Date());
        usersMapper.insert(user);
        return user;
    }

    /**
     * 查询用户登录信息
     * @param userBO 用户登录对象封装实体
     * @return 用户登录对象信息
     */
    @Override
    public Users queryUserLogin(UserBO userBO) {
        String username = userBO.getUsername();
        String password = userBO.getPassword();
        Example example = new Example(Users.class);
        example.createCriteria()
                .andEqualTo("username",username)
                .andEqualTo("password",password);
        return usersMapper.selectOneByExample(example);
    }
}
